<template>
    <div class="main">
        <el-card class="box-card">
            <h3>商品(spu)介绍</h3>
            <el-form style="margin-left:50px" v-model="form" ref="ruleFormRef">
                <el-form-item label="商品名称" label-width="100px" class="is-required">
                    <el-input v-model="form.title " placeholder="请输入商品名称" clearable />
                </el-form-item>
                <el-form-item label="原价" label-width="100px" class="is-required">
                    <el-input v-model="form.originalPrice " :min="0">
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label-width="100px" label="现价" class="is-required">
                    <el-input v-model="form.price " :min="0" >
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label-width="100px" label="VIP价格" class="is-required">
                    <el-input v-model="form.vipPrice " :min="0" >
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label-width="100px" label="库存">
                    <el-input :disabled="true" value='0' />
                </el-form-item>
                <el-form-item label-width="100px" label="运费模板">
                    <el-select v-model="form.freightTemplateId" placeholder="请选择商品状态" clearable>
                        <el-option v-for="item in freightTemplate" :label="item.title" :value="item.id"
                            :key="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label-width="100px" label="是否在售">
                    <el-radio-group v-model="form.status" class="ml-4">
                        <el-radio :label="1" size="large">在售</el-radio>
                        <el-radio :label="0" size="large">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="广告图片:" label-width="100px" class="is-required" id="upload" ref="upload">
                    <el-upload v-model="form.imgList" :headers="headers" :action="action.url" list-type="picture-card"
                        :on-remove="handleRemove" :limit="5" :on-exceed="handlerExceed"
                        :on-success="handleAvatarSuccess">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label-width="100px" label="商品单位" class="is-required">
                    <el-input v-model="form.unit " placeholder="件/个/盒" />
                </el-form-item>
                <el-form-item label-width="100px" label="所属类目">
                    <el-cascader :options="options" :props="props" v-model="form.categoryId" placeholder="请选择商品类目" />
                </el-form-item>
                <el-form-item label-width="100px" label="商品简介">
                    <el-input v-model="form.description " />
                </el-form-item>
                <el-form-item label-width="100px" label="商品详细介绍">
                    <div style="width:100%">
                        <TEditor ref="editor" v-model="form.detail" @getContent="getContent" />
                    </div>
                </el-form-item>
            </el-form>
            <el-card>
                <h4>商品参数</h4>
                <el-button type="primary" @click=" addParamList">添加</el-button>
                <el-table :data="form.attributeList" style="width: 100%">
                    <el-table-column prop="attribute" label="商品参数名称" />
                    <el-table-column prop="value" label="商品参数值" />
                    <el-table-column label="操作" align='center'>
                        <template #default="scope">
                            <el-button type="danger" @click="form.attributeList.splice(scope.$index,1)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            <el-card>
                <h4>规格维度</h4>
                <el-button type="primary" @click="addDimensionList">添加</el-button>
                <el-table :data="form.specificationList" style="width: 100%">
                    <el-table-column label="维度ID" />
                    <el-table-column prop="title" label="维度名称" />
                    <el-table-column label="创建时间">
                        <template #default="scope">
                            <template v-if="scope.row.gmtCreate!=0">
                                {{new Date(scope.row.gmtCreate).friendTime(1)}}
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align='center'>
                        <template #default="scope">
                            <el-button type="primary" @click="handlerEditDimension(scope.row,scope.$index)">编辑
                            </el-button>
                            <el-button type="danger" @click="handlerDeleteDimesion(scope.$index)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            <el-card>
                <h4>商品Sku详情</h4>
                <el-button type="primary" @click="handlerBitchPrice">批量定价</el-button>
                <!-- tag标签 -->
                <div v-for="(item, index) in form.specificationList" class="tag-container">
                    <el-tag style="margin:10px 10px 10px 0px;" type="warning">{{ item.title}}</el-tag>
                    <!-- 可输入标签 -->
                    <el-tag :key="tag" v-for="tag in item.values" closable :disable-transitions="false"
                        @close="handleClose(item,tag)">{{tag}}</el-tag>
                    <el-input class="input-new-tag" v-model="item.inputSkuTagValue" ref="saveTagInput" size="small"
                        @keyup.enter.native="handleInputConfirm(item)" @blur="handleInputConfirm(item)"
                        v-if="item.inputSkuTagVisible"></el-input>
                    <el-button class="button-new-tag ml-1" size="small" @click="showInput(item)">
                        + 添加
                    </el-button>
                </div>
                <el-table :data="form.skuList" :span-method="handlerSpanMethod" style="width: 100%" border>
                    <el-table-column v-for="(item, index) in form.specificationList.filter(item=>item.values.length>0)" :prop="'id_' + item.title"
                        :label="item.title" />
                    <el-table-column prop="skuId" label="SkuId" width="120" align='center' />
                    <el-table-column label="￥价格(元)" width="200" align='center'>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.price" :min="0" />
                        </template>
                    </el-table-column>
                    <el-table-column label="￥VIP价(元)" width="200" align='center'>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.vipPrice" :min="0" />
                        </template>
                    </el-table-column>
                    <el-table-column label="￥吊牌价(元)" width="200" align='center'>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.originalPrice" :min="0" />
                        </template>
                    </el-table-column>
                    <el-table-column label="库存(件)" width="200" align='center'>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.stock" :min="0" />
                        </template>
                    </el-table-column>
                    <el-table-column label="重量(克)" width="200" align='center'>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.weight" :min="0" />
                        </template>
                    </el-table-column>
                    <el-table-column label="SKU图片" width="200" align='center'>
                        <template v-slot="scope">
                            <el-upload :show-file-list="false" :action="action.url"
                                :before-upload="beforeAvatarUpload" :headers="headers"
                                :on-success="handleAvatarSuccesse" :on-remove="handleRemove">
                                <img v-if="scope.row.img" width="50" height="50" :src="scope.row.img" class="avatar">
                                <div v-else @click.capture="changeCurrentRow(scope.$index)">
                                    <el-button type="primary" :icon="Upload "></el-button>
                                </div>
                            </el-upload>
                        </template>
                    </el-table-column>
                    <el-table-column label="条形码" width="200" align='center'>
                        <template #default="scope">
                            <el-input v-model="scope.row.barCode">
                                <template #append>
                                    <el-button @click="scope.row.barCode=new Date().getTime()">随机</el-button>
                                </template>
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-card>
        <el-dialog v-model="dialogFormVisible" :title="title" style="width:35vw">
            <el-form :model="dialogForm" :rules="rules" ref="ruleForm">
                <el-form-item label="设置商品名称" label-width="140px" class="is-required" v-if="num==1" prop="title">
                    <el-input v-model="dialogForm.attribute" autocomplete="off" />
                </el-form-item>
                <el-form-item label="商品参数值" label-width="140px" class="is-required" v-if="num==1" prop="categoryId">
                    <el-input v-model="dialogForm.value" autocomplete="off" />
                </el-form-item>
                <el-form-item label="类型名称" label-width="140px" class="is-required" v-if="num==2" prop="dinmensinonName">
                    <el-input v-model="dialogForm.title" autocomplete="off" @keypress.enter.prevent />
                </el-form-item>
                <el-form-item label="现价（￥）" label-width="140px" v-if="num==3">
                    <el-input-number v-model="dialogForm.price" autocomplete="off"></el-input-number>
                </el-form-item>
                <el-form-item label="vip价格（￥）" label-width="140px" v-if="num==3">
                    <el-input-number v-model="dialogForm.vipPrice" autocomplete="off"></el-input-number>
                </el-form-item>
                <el-form-item label="吊牌价（￥）" label-width="140px" v-if="num==3">
                    <el-input-number v-model="dialogForm.originalPrice" autocomplete="off"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer" v-if="num!=3">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleForm)">确认</el-button>
                </span>
                <span class="dialog-footer" v-else>
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="resure">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 底部提交按钮 -->
        <div class="bottom-wrap">
            <el-button type="primary">关闭</el-button>
            <el-button type="primary" @click="keepGoods">保存商品</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { Plus, Upload } from '@element-plus/icons-vue'//图标
import { reactive, ref, nextTick } from "vue";
import type { FormInstance, UploadProps } from 'element-plus';
import { ElMessage, ElInput } from 'element-plus'//element-plus消息提示
import { post } from "@/utils/request";
import cookie from 'js-cookie'//引入cookie
import TEditor from '@/components/tinymce/TEditor.vue';
import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'
import { ClassAddCommodityListData, ClassSpecificationList, ClassSkuList } from "#/index";
import "@/utils/dataFriend"
interface User {
    id: string
    name: string
    amount1: string
    amount2: string
    weight: number
    skuImg: string
    barCode: number
    originalPrice: number
}
interface SpanMethodProps {
    row: User
    column: TableColumnCtx<User>
    rowIndex: number
    columnIndex: number
}
let options: TypeAdOptions[] = reactive([])//类目列表
let freightTemplate: TypeFreightTemplateId[] = reactive([])//运费列表
const ruleFormRef = ref<FormInstance>()//表单组件的引用对象
const ruleForm = ref<FormInstance>()
let dialogFormVisible = ref(false)
let num = ref(1)//商品参数，维度，定价标识
let props = reactive({//类目列表配置
    emitPath: false,//返回该节点的值
    checkStrictly: true,//父子节点是否关联
    children: 'childrenList',
    label: 'title',
    value: 'id',
})
let title = ref('')
let form = reactive(new ClassAddCommodityListData())//表单数据
let dialogForm = reactive({  //弹出框数据
    attribute: '',
    value: '',
    title: '',
    price: 0,
    vipPrice: 0,
    originalPrice: 0,
})
let cloneDialogForm = { ...dialogForm }   //克隆弹出框数据
const headers = reactive({  //上传图片获取请求头
    AdminToken: cookie.get('token')
})
const getContent = (v: string) => {
    form.detail = v
}
let indexRow = 0
const InputRef = ref<InstanceType<typeof ElInput>>()
let skuLength = ref(0);//总共生成多少个数据，有多少行
/**
 * 生成skus
 */
let skuDataList = () => {
    const skuTagsList = form.specificationList.filter((item) => item.values.length).map((v) => v.values) //过滤掉商品维度数据里面的tags数组
    let name = form.specificationList.filter((item) => item.values.length).map((item) => item.title)//获取到商品维度数组里面所有的title（维度名称）
    if (skuTagsList.length == 0) {
        form.skuList = []
        return
    }
    console.log(skuTagsList);
    
    let arr = skuTagsList.reduce((total: string[][], current) => {
        let array: string[][] = []
        total.forEach(v1 => {
            current.forEach(item => {
                array.push(v1.concat([item]))
            })
        })
        return array
    }, [[]])
    // console.log(arr);

    let list = arr.map(v => {
        let obj = {
            title: '',
            price: 0,
            originalPrice: 0,
            vipPrice: 0,
            stock: 0,
            img: '',
            weight: 0,
            specificationAry: new Array<string>(),
            specification: '',
            barCode: 0,
            titleArray: new Array<string>(),
            titles: []
        }
        v.forEach((v1, index: number) => {
            let key = 'id_' + name[index]
            obj[key] = v1
            obj.titleArray.push(v1)
            obj.specificationAry.push(name[index] + '_' + v1)
        })
        obj.title = obj.titleArray.join(',')
        obj.specification = obj.specificationAry.join(',')
        let findItem = form.skuList.find(item => item.specification === obj.specification)
        console.log(findItem)
        console.log(obj)
        if (findItem) {
            return findItem
        }

        let skuObj = new ClassSkuList()
        Object.assign(skuObj, obj)
        return skuObj
    })
    skuLength.value = list.length
    form.skuList.length = 0
    form.skuList.push(...list)
    console.log(form.specificationList);


    // const skuTagsList = form.specificationList.filter((item: ClassSpecificationList) => item.values.length).map(v => v.values) //过滤掉商品维度数据里面的tags数组
    // const name = form.specificationList.filter(v=>v.values.length).map((item: ClassSpecificationList) => item.title)//获取到商品维度数组里面所有的title（维度名称）

    // // 使用笛卡尔积算法将数据进行交叉处理
    // let arr = skuTagsList.reduce(
    //     (total:string[][], current) => {
    //         let temp:string[][] = []
    //         total.forEach(item => {
    //             current.forEach(value => {//拿到skuTagsList数组里面的每个维度名称
    //                 temp.push(item.concat([value]))//将其
    //             })
    //         })
    //         return temp
    //     },[[]])
    // // 进行拼接数据
    // let list = arr.map(item => {
    //     let obj = new ClassSkuList()
    //     item.forEach((val, index: number) => {
    //         // 相当于是添加一个对象
    //         obj['id_' + name[index]] = val
    //         obj['title'] = item.join(',')
    //         obj.specification += form.specificationList[index].title + '_' + val + ','
    //     })
    //     obj.title = obj.title.slice(0, obj.title.length - 1)
    //     return obj
    // })
    // //生成的数组长度赋值给skuLength，即表格要生成的行数
    // skuLength.value = list.length
    // form.skuList.length = 0
    // form.skuList.push(...list)
}

function keepGoods() {
    let data = {
        _gp: 'admin.product',
        _mt: 'create',
        spuDTO: JSON.stringify(form)
    }
    console.log(form);
    post(data).then((res) => {
        // console.log(res);
        ElMessage.success('添加成功')
    })
}
/**
 * 表格跨行跨列
 */
function handlerSpanMethod({ row, column, rowIndex, columnIndex }: SpanMethodProps) {
    // //第三种方法
    // let newFormSkuList = form.specificationList.filter(v => v.values.length > 0)
    // let rowspan = form.skuList.length
    // for (let index = 0; index < newFormSkuList.length; index++) {
    //     rowspan /= newFormSkuList[index].values.length
    //     if (columnIndex === index) {
    //         if (rowIndex % rowspan === 0) { //每次跨行的数量相同,所以当前行索引号%跨行数量==0就是要跨行的开始
    //             return { rowspan: rowspan, colspan: 1 }
    //         } else {
    //             return { rowspan: 0, colspan: 0 }
    //         }
    //     }
    // }


    //第二种方法
    let specList = form.specificationList.filter(item=>item.values.length>0) //获取规格列表
    if(columnIndex<specList.length-1){  //对要跨行的列进行计算，排除最后一个属性列(最后一个属性不存在)
      let rowSpanNum = 1 //跨行的数量
      for (let index = columnIndex+1; index < specList.length; index++) {
        rowSpanNum*= specList[index].values.length  //跨行的数量-后面属性值数量的成绩
        }
        if(rowIndex%rowSpanNum===0){ //每次跨行的数量相同,所以当前行索引号%跨行数量==0就是要跨行的开始
            return {rowspan:rowSpanNum,colspan:1};
        }else{
            return {rowspan:0,colspan:0};
        }
    }
    
    // 第一种方法
    // 拿到第一列要合并的行数
    // let rowspan = skuLength.value / form.specificationList[0].values.length
    // for (let index = 0; index < form.specificationList.length; index++) {
    //     if (index !== 0) {
    //         //依次拿到每一列要合并的行数
    //         rowspan = rowspan / form.specificationList[index].values.length;
    //     }
    //     if (columnIndex === index) {
    //         //当条件成立时，即合并行数
    //         if (rowIndex % rowspan === 0) {
    //             return {
    //                 //合并的行数配置
    //                 rowspan: rowspan,
    //                 colspan: 1
    //             }
    //         } else {
    //             return {
    //                 rowspan: 0,
    //                 colspan: 0
    //             };
    //         }
    //     }
    // }
}
//删除tag标签页
const handleClose = (item: ClassSpecificationList, index: string) => {
    item.values.splice(item.values.indexOf(index), 1);
    form.specificationList[0].values.length!=0?skuDataList(): form.skuList.length=0
}
/**
 * 显示输入框
 */
const showInput = (item: ClassSpecificationList) => {
    item.inputSkuTagVisible = true;
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
/**
 * 输入框失焦事件
 */
const handleInputConfirm = (item: ClassSpecificationList) => {
    let inputValue = item.inputSkuTagValue;
    if (inputValue) {
        //往当前的tags数组添加tag
        item.values.push(inputValue);
    }
    skuDataList()
    item.inputSkuTagVisible = false;
    item.inputSkuTagValue = '';
}
//表单验证
const validateTitle = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        return callback(new Error('内容不能为空'))
    } else {
        callback()
    }
}
//失焦触发验证
const rules = reactive({
    paramName: [{ validator: validateTitle, trigger: 'blur' }],
    paramId: [{ validator: validateTitle, trigger: 'blur' }],
    dinmensinonName: [{ validator: validateTitle, trigger: ['change'] }],
})
/**
 * 显示类目列表
 */
function handlerShowCategory() {
    let categoryData = {
        _gp: 'admin.category',
        _mt: 'categoryTree',
    }
    post(categoryData).then(res => {
        options.length = 0;
        options.push(...res.data)
        console.log(res)
    })
}
handlerShowCategory()
/**
 * 显示运费列表
 */
function handlerShowFreight() {
    let freightData = {
        _gp: 'admin.freight',
        _mt: 'list',
    }
    post(freightData).then(res => {
        freightTemplate.length = 0;
        freightTemplate.push(...res.data)
        console.log(res)
    })
}
handlerShowFreight()
/**
 * 商品参数确认
 */
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            dialogFormVisible.value = false
            if (1 === num.value) {
                form.attributeList.push({ attribute: dialogForm.attribute, value: dialogForm.value })
            } else if (2 === num.value && title.value == '创建规格维度') {
                let obj = new ClassSpecificationList()
                obj.title = dialogForm.title;
                obj.gmtCreate = new Date().getTime(),
                    form.specificationList.push(obj)
                    skuDataList()
            } else if (2 === num.value && title.value == '修改规格维度') {
                form.specificationList[indexRow].title = dialogForm.title
                skuDataList()
            }
        }
    })

}
/**
 * 商品规格删除
 */
function handlerDeleteDimesion(index: number) {
    form.specificationList.splice(index, 1)
    form.specificationList.length==0||form.specificationList[0].values.length==0?form.skuList.length=0:skuDataList()
}
/**
 * 商品定价验证
 */
function resure() {
    if (dialogForm.vipPrice < dialogForm.price && dialogForm.vipPrice < dialogForm.originalPrice && dialogForm.price < dialogForm.originalPrice) {
        form.skuList.map((v: ClassSkuList) => {
            v.price = dialogForm.price;
            v.vipPrice = dialogForm.vipPrice;
            v.originalPrice = dialogForm.originalPrice
        })
    } else {
        return ElMessage.warning('批量定价vip价格必须小于现价并且vip价格小于原价并且现价小于原价!')
    }
    dialogFormVisible.value = false
}
const changeCurrentRow = (index: number) => {
    indexRow = index
}
/**
 * 商品维度编辑
 */
function handlerEditDimension(row: ClassSpecificationList, index: number) {
    console.log(row)
    num.value = 2
    title.value = '修改规格维度'
    indexRow = index
    dialogFormVisible.value = true
    dialogForm.title = row.title as string
}
/**
 * 商品参数确认
 */
function addParamList() {
    num.value = 1
    title.value = '设置商品参数'
    dialogFormVisible.value = true
    Object.assign(dialogForm, cloneDialogForm)
}
/**
 * 商品维度确认
 */
function addDimensionList() {
    dialogFormVisible.value = true
    num.value = 2
    title.value = '创建规格维度'
    Object.assign(dialogForm, cloneDialogForm)

}
/**
 * 批量定价
 */
function handlerBitchPrice() {
    num.value = 3
    dialogFormVisible.value = true
    title.value = '批量定价'
}

const action = reactive({ //判断环境修改上传图片路径
    url: process.env.NODE_ENV === 'development' ? '/upload/admin' : 'http://zxwyit.cn:8989/upload/admin'
})

/**
 * 广告上传图片成功之后的函数
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (     
    response,
    uploadFile
) => {
    if (200 == response.errno) {
        let url = response.url
        form.img = response.url // 得到上传图片成功的路径
        form.imgList.push(url)
    }
}
/**
 * SKU上传图片成功之后的函数
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const handleAvatarSuccesse: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (200 == response.errno) {
        form.skuList[indexRow].img = response.url // 得到上传图片成功的路径
    }
}
/**
 * 删除成功之后的函数
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let imgList = uploadFiles.map(item=>item.response.url)
    form.imgList = imgList
}

/**
 * 图片超出数量之后的函数
 * @param files 上传的文件
 */
const handlerExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning('图片数量不能超过5张')
}
/**
 * 上传图片之前的函数判断
 * @param response 响应成功的回调
 * @param uploadFile 上传的文件
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    let imgar = rawFile.type === 'image/jpeg' || rawFile.type === 'image/jpg' || rawFile.type === 'image/png'
    if (!imgar) {
        ElMessage.error('格式错误!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
</script>
<style lang="less" scoped>
.page-container {
    height: calc(100vh - 142px);
    overflow: auto;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

&::v-deep .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.tag-container {

    .el-tag+.el-tag {
        margin-left: 10px;
    }

    &::v-deep .el-button {
        margin-left: 10px;
        height: 30px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: middle;
    }
}

.bottom-wrap {
    text-align: right;
    margin: 15px 0 20px 0;
}
</style>